import { defineStore } from 'pinia'
import router from '@/router'
import { ElMessage } from 'element-plus'

export const navTab = defineStore({
  id: 'navTab',
  state: () => {return {
    tabs:[
     { name: '主页',path:"/main",clicked:true},
    ],
    current:"",
    currentTab:null
   }
  },

  getters: {
    getTabs: (state) => state
  },

  actions: {
    routeTo(item) {
      let exist = false
      this.tabs.forEach(tab => {
        if(tab.path === item.path){
         tab.clicked = true
          exist = true
        }else{
          tab.clicked = false
        }
      })

      if(!exist){
        console.log(this.tabs.length )
        if(this.tabs.length > 12){
          ElMessage.error("打开的页签过多！")
          return false
        }
        this.tabs.push(item)
      }
      router.push(item.path)
      this.current = item.name
      this.currentTab = item
      return true
    },
    removeTab(item) {
      let preItem = null
      let purTabs = this.tabs
      for(let i=0; i<purTabs.length; i++){
        let curr = purTabs[i]
        if(curr.path === item.path){
          purTabs.splice(i,1)
          break
        }else{
          preItem = curr
        }
      }
      if(item.clicked){
        this.routeTo(preItem)
      }
    },
    clear() {
      this.tabs = []
      this.current = ""
      this.currentTab = null
    }
  }
})